30. 字典和恒等运算符
L2 02 Dictionaries And Identiy Operators V3
字典和恒等运算符
字典
字典 是可变数据类型,其中存储的是唯一键到值的映射。下面是存储元素和相应原子序数的字典。
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}字典的键可以是任何不可变类型,例如整数或元组,而不仅仅是字符串。甚至每个键都不一定要是相同的类型!我们可以使用方括号并在括号里放入键,查询字典中的值或向字典中插入新值。
print(elements["helium"])  # print the value mapped to "helium"
elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary
          我们可以像检查某个值是否在列表或集合中一样,使用关键字
          
           in
          
          检查值是否在字典中。字典有一个也很有用的相关方法,叫做
          
           get
          
          。get 会在字典中查询值,但是和方括号不同,如果没有找到键,get 会返回 None(或者你所选的默认值)。
         
print("carbon" in elements)
print(elements.get("dilithium"))输出结果为:
True
None
          Carbon 位于该字典中,因此输出 True。Dilithium 不在字典中,因此
          
           get
          
          返回 None,然后系统输出 None。如果你预计查询有时候会失败,
          
           get
          
          可能比普通的方括号查询更合适,因为错误可能会使程序崩溃。
         
恒等运算符
| 关键字 | 运算符 | 
|---|---|
| 
              is
              | 检查两边是否恒等 | 
| 
              is not
              | 检查两边是否不恒等 | 
          你可以使用运算符
          
           is
          
          检查某个键是否返回了 None。或者使用
          
           is not
          
          检查是否没有返回 None。
         
n = elements.get("dilithium")
print(n is None)
print(n is not None)会输出:
True
False